<template>
  <div class="product-detail">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-position="right"
      label-width="130px"
    >
      <div class="form-data">
        <el-tabs type="border-card">
          <el-tab-pane label="商品基本信息">
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="postForm.title"
                placeholder="标题"
                style="width: 100%"
                :maxlength="100"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="主图" prop="main_image">
              <tn-image-item
                ref="imageItem"
                v-model="postForm.main_image"
                placeholder="主图"
                style="width: 100%"
                :limit="9"
              />
            </el-form-item>
            <el-form-item label="所属分类" prop="category_id">
              <el-select
                v-model.number="postForm.category_id"
                placeholder="所属分类"
                style="width: 100%"
                @change="getCategoryCount"
              >
                <el-option v-for="item in categoryOptions" :key="'shop_product_detail_' + item.id" :value="item.id" :label="item.title" />
              </el-select>
            </el-form-item>
            <el-form-item label="关键词" prop="keyword">
              <el-input
                v-model="postForm.keyword"
                type="textarea"
                placeholder="关键词"
                style="width: 100%"
                :maxlength="255"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="描述" prop="desc">
              <el-input
                v-model="postForm.desc"
                type="textarea"
                placeholder="描述"
                style="width: 100%"
                :maxlength="255"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="虚拟商品" prop="virtual_product">
              <el-switch
                v-model.number="postForm.virtual_product"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
            <el-form-item label="销量" prop="sales_volume">
              <el-input-number
                v-model.number="postForm.sales_volume"
                :disabled="true"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item label="虚拟销量" prop="virtual_sales_volume">
              <el-input-number
                v-model.number="postForm.virtual_sales_volume"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model.number="postForm.sort"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item label="推荐" prop="recomm">
              <el-switch
                v-model.number="postForm.recomm"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model.number="postForm.status"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-tab-pane>
          <!-- 详情 -->
          <el-tab-pane label="详情管理">
            <tn-form-item
              v-model="postForm.content"
              :type="6"
              label="详情内容"
              name="content"
              save-dir-name="tn_shop_product_content"
            />
          </el-tab-pane>
          <!-- sku -->
          <el-tab-pane label="sku管理">
            <el-row>
              <el-button type="success" @click="addProductProperty">增加属性</el-button>
              <el-button type="success" @click="addProductSpecs">增加规格</el-button>
            </el-row>
            <el-table
              :data="postForm.specs"
              height="400"
            >
              <el-table-column
                label="产品图"
                width="140"
              >
                <template slot-scope="{ row }">
                  <tn-image-item
                    ref="imageItem"
                    v-model="row.product_image"
                    class="product-specs-image"
                    placeholder="产品图"
                    style="width: 80%"
                    :limit="1"
                  />
                </template>
              </el-table-column>
              <!-- 商品属性 -->
              <el-table-column
                v-for="(property_item, property_index) in postForm.property"
                :key="property_item.prop"
              >
                // eslint-disable-next-line vue/no-unused-vars
                <template slot="header" slot-scope="scope">
                  <el-input
                    v-model="property_item.name"
                    size="mini"
                    clearable
                    max="10"
                    placeholder="商品属性"
                  >
                    <el-button slot="append" class="property-del" icon="el-icon-circle-close" @click="deleteProductProperty(property_index)" />
                  </el-input>
                </template>
                <template slot-scope="{ row }">
                  <el-input
                    v-model="row[property_item.prop]"
                    size="mini"
                    clearable
                    max="30"
                    :placeholder="property_item.name"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="原价"
                width="140"
              >
                <template slot-scope="{ row }">
                  <el-input-number
                    v-model.number="row.original_price"
                    type="number"
                    controls-position="right"
                    size="mini"
                    :step="0.01"
                    :min="0"
                    placeholder="原价"
                  >
                    <span slot="prepend">¥</span>
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                label="售价"
                width="140"
              >
                <template slot-scope="{ row }">
                  <el-input-number
                    v-model.number="row.selling_price"
                    type="number"
                    controls-position="right"
                    :step="0.01"
                    size="mini"
                    :min="0"
                    placeholder="售价"
                  >
                    <template slot="prepend">¥</template>
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                label="库存"
                width="140"
              >
                <template slot-scope="{ row }">
                  <el-input-number
                    v-model.number="row.stock"
                    type="number"
                    controls-position="right"
                    size="mini"
                    :min="0"
                    placeholder="库存"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template slot-scope="{ $index }">
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteProductSpecs($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 参数管理 -->
          <el-tab-pane label="参数管理">
            <el-row>
              <el-button type="success" @click="addProductParameters">增加参数</el-button>
            </el-row>
            <el-table
              :data="postForm.parameters"
              height="400"
            >
              <el-table-column
                label="参数名"
                width="160"
              >
                <template slot-scope="{ row }">
                  <el-input
                    v-model="row.name"
                    clearable
                    max="30"
                    placeholder="请输入参数名"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="参数值"
              >
                <template slot-scope="{ row }">
                  <el-input
                    v-model="row.value"
                    clearable
                    max="100"
                    placeholder="请输入参数值"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template slot-scope="{ $index }">
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteProductParameters($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>

      <sticky :class-name="'sub-navbar'">
        <el-button
          v-loading="loading"
          type="success"
          style="margin-left: 10px"
          @click="submitForm"
        >
          {{ isEdit ? '编辑' : '添加' }}
        </el-button>
      </sticky>
    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import TnUploadImageItem from '@/components/TNUploadImageItem'
import TnFormItem from '@/components/TNFormItem'
import { getAllCategoryTitle } from '@/api/shop-category'
import { getProductByID, getProductCountByCategoryID, addProduct, editProduct } from '@/api/shop-product'

const fields = {
  title: '标题',
  keyword: '关键词',
  desc: '描述',
  content: '详细内容'
}

const validateRequire = (rule, value, callback) => {
  if (!value || value === '' || value.trim() === '') {
    const errMsg = fields[rule.field] + '为必填项'
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

export default {
  name: 'ShopProductDetail',
  components: { Sticky, 'tn-image-item': TnUploadImageItem, TnFormItem },
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isEdit: false,
      loading: false,
      productPropertyKeyLength: 0,
      categoryOptions: [],
      postForm: {
        title: '',
        main_image: [],
        keyword: '',
        desc: '',
        content: '',
        virtual_product: 0,
        sales_volume: 0,
        virtual_sales_volume: 0,
        category_id: '',
        sort: 1,
        recomm: 0,
        status: 1,
        property: [],
        specs: [],
        parameters: []
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        main_image: [
          { required: true, message: '主图不能为空' }
        ],
        keyword: [
          { required: true, message: '关键词不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '描述不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        virtual_product: [
          { required: true, message: '虚拟商品不能为空' },
          { type: 'number', message: '虚拟商品值格式不正确' }
        ],
        recomm: [
          { required: true, message: '推荐不能为空' },
          { type: 'number', message: '推荐值格式不正确' }
        ],
        sort: [
          { required: true, message: '排序不能为空' },
          { type: 'number', message: '排序值格式不正确' }
        ],
        status: [
          { required: true, message: '状态不能为空' },
          { type: 'number', message: '状态值格式不正确' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          // 判断规则是否通过验证
          if (valid &&
              this._checkParametersData() &&
              this._checkPropertyData() &&
              this._checkSpecsData()
          ) {
            const product = Object.assign({}, this.postForm)
            // console.log(menu)
            if (!this.isEdit) {
              addProduct(product).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            } else {
              product.id = this.id
              editProduct(product).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            this.loading = false
            for (const key in fields) {
              if (fields.hasOwnProperty(key)) {
                const element = fields[key]
                this.$message({
                  message: element[0].message,
                  type: 'error',
                  duration: 2000
                })
                return false
              }
            }
          }
        })
      }
    },
    getProductByID() {
      if (this.id !== 0) {
        getProductByID(this.id).then(response => {
          if (!response.data || response.data.length === 0) {
            this.isEdit = false
            // this.changeCategory(0)
            return
          }
          const {
            title,
            main_image,
            keyword,
            desc,
            content,
            virtual_product,
            sales_volume,
            virtual_sales_volume,
            category_id,
            sort,
            recomm,
            status,
            property,
            specs,
            parameters
          } = response.data
          this.postForm = {
            title,
            main_image: main_image.value,
            keyword,
            desc,
            content,
            virtual_product,
            sales_volume,
            virtual_sales_volume,
            category_id,
            sort,
            recomm,
            status,
            property: [],
            specs: [],
            parameters: []
          }
          // 处理商品属性和规格数据
          this.handleServiceData(property, specs, parameters)
          this.isEdit = true
        }).catch(() => {
          this.isEdit = false
          // this.changeCategory(0)
          this.toDefault()
        })
      } else {
        // this.changeCategory(0)
        this.isEdit = false
      }
    },
    toDefault() {
      this.$refs.postForm.resetFields()
      this.postForm.property = []
      this.postForm.specs = []
      this.loading = false
    },
    async getAllCategoryTitle() {
      const category_data = await getAllCategoryTitle()
      this.categoryOptions = category_data.data
      this.getProductByID()
    },
    getCategoryCount(value) {
      if (!this.id) {
        getProductCountByCategoryID(value).then((response) => {
          const { count } = response
          this.postForm.sort = count + 1
        })
      }
    },
    handleServiceData(property, specs, parameters) {
      // console.log(property, specs)
      const property_data = []
      const property_prop_key = []
      const specs_data = []
      const parameters_data = []

      property.forEach((item) => {
        const property_key = 'property_' + (this.productPropertyKeyLength++)
        property_data.push({
          id: item.id,
          name: item.name,
          prop: property_key
        })
        property_prop_key[item.id] = property_key
      })

      specs.forEach((item) => {
        const specs_base_data = {
          id: item.id,
          product_image: item.product_image.value || '',
          original_price: item.original_price,
          selling_price: item.selling_price,
          stock: item.stock
        }
        const specs_property_data = {}
        item.property.forEach((prop_item) => {
          specs_property_data[property_prop_key[prop_item.property_id]] = prop_item.value
        })
        specs_data.push(Object.assign(specs_base_data, specs_property_data))
      })

      parameters.forEach((item) => {
        parameters_data.push({
          name: item.name,
          value: item.value
        })
      })
      // console.log(property_data, specs_data)

      this.postForm.property = JSON.parse(JSON.stringify(property_data))
      this.postForm.specs = JSON.parse(JSON.stringify(specs_data))
      this.postForm.parameters = JSON.parse(JSON.stringify(parameters_data))
    },
    addProductProperty() {
      const property_key = 'property_' + (this.productPropertyKeyLength++)
      // 往属性表中添加数据
      const property = this.postForm.property
      property.push({
        id: 0,
        prop: property_key,
        name: ''
      })
      // 如果存在规格，则往规格中添加属性字段
      const specs = this.postForm.specs
      specs.forEach((item) => {
        // item[property_key] = ''
        this.$set(specs, item[property_key], '')
      })
      // 要深拷贝数据，要不然可以会出现输入框无法输入的情况
      this.postForm.property = JSON.parse(JSON.stringify(property))
      this.postForm.specs = JSON.parse(JSON.stringify(specs))
      this.$forceUpdate()
    },
    addProductSpecs() {
      // 判断商品规格是否为空
      if (this.postForm.property.length === 0 && this.postForm.specs.length >= 1) {
        this.$notify({
          title: '提示',
          message: '没有属性时，商品规格只能添加一种',
          type: 'warning'
        })
        return
      }

      const specs = this.postForm.specs
      const base_specs_data = {
        id: 0,
        product_image: '',
        original_price: 0,
        selling_price: 0,
        stock: 0
      }
      // 循环添加属性
      this.postForm.property.forEach((item) => {
        const item_prop = item.prop
        base_specs_data[item_prop] = ''
      })

      specs.push(base_specs_data)
      this.postForm.specs = [...specs]
      this.$forceUpdate()
    },
    addProductParameters() {
      const parameters = this.postForm.parameters
      parameters.push({
        name: '',
        value: ''
      })

      this.postForm.parameters = JSON.parse(JSON.stringify(parameters))
      this.$forceUpdate()
    },
    deleteProductProperty(index) {
      const item_prop = this.postForm.property[index].prop
      const property = this.postForm.property
      const specs = this.postForm.specs
      // 删除对应的属性
      property.splice(index, 1)
      // 删除商品规格里面的属性数据
      specs.forEach((item) => {
        delete item[item_prop]
      })
      this.postForm.property = [...property]
      this.postForm.specs = [...specs]
      this.$forceUpdate()
    },
    deleteProductSpecs(index) {
      const specs = this.postForm.specs

      // 删除商品规格
      specs.splice(index, 1)

      this.postForm.specs = [...specs]
      this.$forceUpdate()
    },
    deleteProductParameters(index) {
      const parameters = this.postForm.parameters

      // 删除商品参数
      parameters.splice(index, 1)

      this.postForm.parameters = JSON.parse(JSON.stringify(parameters))
      this.$forceUpdate()
    },
    _checkPropertyData() {
      const check = this.postForm.property.some((item) => {
        if (item.name === '') {
          return true
        }
      })
      if (check) {
        this.$message({
          message: '请移除空的商品属性后再提交',
          type: 'error'
        })
      }

      return !check
    },
    _checkSpecsData() {
      if ((this.postForm.property.length === 0 && this.postForm.specs.length < 1) ||
        this.postForm.specs.length === 0
      ) {
        this.$message({
          message: '请添加商品规格信息',
          type: 'error'
        })
        return false
      }
      const property = this.postForm.property.map((item) => {
        return item.prop
      })

      const check = this.postForm.specs.some((item) => {
        return property.some((prop_item) => {
          if (item[prop_item] === '') {
            return true
          }
        })
      })
      if (check) {
        this.$message({
          message: '请移除空的商品规格后再提交',
          type: 'error'
        })
      }

      return !check
    },
    _checkParametersData() {
      const check = this.postForm.parameters.some((item) => {
        if (item.name === '' || item.value === '') {
          return true
        }
      })
      if (check) {
        this.$message({
          message: '请移除空的商品参数后再提交',
          type: 'error'
        })
      }

      return !check
    }
  }
}
</script>

<style lang="scss" scoped>
div>>>.el-input-group__append {
  padding:0 12px;
}
div>>>.el-input-group__prepend {
  padding: 0 12px;
}
.product-specs-image >>> .el-image {
  width: 80px !important;
  height: auto !important;
  margin-left: 0px !important;
}
.property-del {
  padding:0 13px;
}
</style>
